package com.jiangjiang.eshop.wms.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jiangjiang.eshop.wms.convert.PurchaseInputOrderItemConvert;
import com.jiangjiang.eshop.wms.dao.PurchaseInputOrderItemMapper;
import com.jiangjiang.eshop.wms.domain.PurchaseInputOrderItem;
import com.jiangjiang.eshop.wms.dto.PurchaseInputOrderItemDTO;
import com.jiangjiang.eshop.wms.dto.PurchaseInputOrderPutOnItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName PurchaseInputOrderItemService
 * @Description TODO
 * @Author jhw
 * @Date 2021/9/13 21:52
 * @Version 1.0
 **/
@Service
public class PurchaseInputOrderItemService extends ServiceImpl<PurchaseInputOrderItemMapper, PurchaseInputOrderItem> {
    @Autowired
    private PurchaseInputOrderItemConvert purchaseInputOrderItemConvert;
    @Autowired
    private PurchaseInputOrderPutOnItemService purchaseInputOrderPutOnItemService;


    /**
     * 批量保存采购入库单明细数据
     * @param items
     */
    public void saveOrUpdateBatch(List<PurchaseInputOrderItemDTO> items) {
        this.saveOrUpdateBatch(purchaseInputOrderItemConvert.convertDTOList2Entities(items));
    }


    /**
     * 根据采购入库单查询采购入库单明细数据
     * @param purchaseInputOrderId 采购入库单id
     * @return 查询结果
     */
    public List<PurchaseInputOrderItemDTO> queryByPurchaseInputOrderId(Long purchaseInputOrderId) {
        // 查询入库明细记录
        LambdaQueryWrapper<PurchaseInputOrderItem> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PurchaseInputOrderItem::getPurchaseInputOrderId, purchaseInputOrderId);
        List<PurchaseInputOrderItem> items = this.list(wrapper);
        List<Long> itemIds = items.stream().map(PurchaseInputOrderItem::getId).collect(Collectors.toList());
        // 根据入库单明细记录查询上架明细记录并且按照入库单明细id分组
        Map<Long, List<PurchaseInputOrderPutOnItemDTO>> putOnItemMap = purchaseInputOrderPutOnItemService.queryByItemIds(itemIds)
                .stream()
                .collect(Collectors.groupingBy(PurchaseInputOrderPutOnItemDTO::getPurchaseInputOrderItemId));
        // 组合入库明细DTO集合
        return purchaseInputOrderItemConvert.convertEntities2DTOList(items)
                .stream()
                .peek(itemDTO -> itemDTO.setPutOnItems(putOnItemMap.getOrDefault(itemDTO.getId(), Lists.newArrayList())))
                .collect(Collectors.toList());

    }
}
